package com.xian.im.message.queue;

import com.xian.im.common.enums.ConsumerQueueEnum;
import com.xian.im.common.proto.MsgRequest;
import com.xian.im.message.model.QueueMsg;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @program: xian-code
 * @description:  消息队列
 * @author: liru.xian
 * @create: 2021-01-19 14:46
 **/
@Slf4j
public class MessageGroupQueue {

    private static Map<String , LinkedBlockingQueue> map = new ConcurrentHashMap<>();

    /**
     *  群消息消费
     * @param groupAccount
     * @return
     */
    public static QueueMsg take(String groupAccount){
        try {
            LinkedBlockingQueue<List<MsgRequest>> queue = map.get(groupAccount);
            if(queue!=null){
                return (QueueMsg) map.get(groupAccount).take();
            }else {
                LinkedBlockingQueue<QueueMsg> blockingQueue = new LinkedBlockingQueue<>();
                map.put(groupAccount,blockingQueue);
                return blockingQueue.take();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  群消息发送队列
     * @param obj
     * @param groupAccount
     */
    public static void  put(QueueMsg obj, String groupAccount){
        try {
            LinkedBlockingQueue<QueueMsg> queue = map.get(groupAccount);
            if(queue!=null){
                queue.put(obj);
            }else {
                LinkedBlockingQueue<QueueMsg> blockingQueue = new LinkedBlockingQueue<QueueMsg>();
                map.put(groupAccount,blockingQueue);
                blockingQueue.put(obj);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return
     */
    public static ConsumerQueueEnum getType() {
        return ConsumerQueueEnum.CONSUMER_GROUP;
    }

    public static Map<String ,LinkedBlockingQueue> getMap(){
        return map;
    }

    public static void init(Set<String> strings){
          for (String string : strings) {
              LinkedBlockingQueue<QueueMsg> queue = map.get(string);
              if(queue ==null){
                  LinkedBlockingQueue<QueueMsg> blockingQueue = new LinkedBlockingQueue<QueueMsg>();
                  map.put(string,blockingQueue);
              }
          }
    }
}
